<?php


namespace app\service;

use app\model\ModelUserAccountCard;
use app\model\ModelUserAccountIncome;
use app\model\ModelUserVipLog;
use think\facade\Db;
use app\model\ModelUser;
use app\model\ModelUserAccount;
use app\model\ModelUserLoginLog;
use app\model\ModelUserTask;

/**
 * 用户服务类
 * Class UserService
 * @package app\service
 */
class UserService extends BaseService
{

    /**
     * UserService constructor.
     */
    //private function __construct()
    //{
   // }



    /**
     * 创建用户数据
     * @param array $data 用户数据对象数组
     * @return int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function createUser(array $data) : array {
        if(!empty($data['mobile'])){
           $isHave = $this -> isHaveUserMobile($data['mobile']);
           if($isHave){
            return $this -> error('手机号已存在',1);
           }
        } //password
        $equipment_name =  $data['equipment_name'];
        $login_ip = $data['login_ip'];
        $userModel = new ModelUser();
        $reg_time = time();
        $token = md5($data['mobile'].$data['password'].$reg_time.$equipment_name.$login_ip); //创建用于识别用户
        $data['reg_time'] =$reg_time;
        $data['user_token'] = $token;
        $data['is_delete'] = 1;  //逻辑删除 1:未删除 2 已删除
        $data['my_invitation_code'] = $this ->getInvitationCode();
        //$data['lv'] = 1;//用户团队级别
        unset($data['equipment_name']);//用户主表没这个字段
        unset($data['login_ip']);//用户主表没这个字段
        $result_id = $userModel -> insertGetId($data);
        $regMsg = '';
        if($result_id){
            //给用户账号表初始化一条数据
            $result_account_result = $this -> insertUserAccount($result_id);
            if($result_account_result){
                $regMsg = '恭喜您，注册成功';
                $datalog = [
                    'user_id' => $result_id,
                    'login_ip' => $login_ip,
                    'login_time' => $reg_time,
                    'login_status' => 0,
                    'login_num' =>  1, //todo
                    'equipment_name' => $equipment_name,
                    'remark' => '创建用户：' . $regMsg . ',用户数据：' . json_encode($data),
                ];
                //var_dump($datalog);
                //如果日志插入失败，则不管
                $this -> insertUserLoginLog($datalog);
                return $this -> success($regMsg,$result_id);
            }else{
                $regMsg = '抱歉，注册失败（初始化）';
                $datalog = [
                    'user_id' => $result_id,
                    'login_ip' => $login_ip,
                    'login_time' => $reg_time,
                    'login_status' => 0,
                    'login_num' =>  1, //todo
                    'equipment_name' => $equipment_name,
                    'remark' => '创建用户：' . $regMsg . ',用户数据：' . json_encode($data),
                ];
                //如果日志插入失败，则不管
                $this -> insertUserLoginLog($datalog);
                return $this -> error($regMsg);
            }
        }else{
            $regMsg = '抱歉，注册失败';
            return  $this -> error($regMsg);
        }
    }

    /**
     * 根据推广人的编码获取推广人信息
     * @param string $invitation_code
     * @return array
     */
   public function getUserByInvitationCode(string $invitation_code) : array{
//TODO
   }


    /**
     * 用户登录专用服务方法
     * @param string $mobile 手机号
     * @param string $pwd 密码
     * @param string $login_ip 登录IP
     * @param string $equipment_name 设备名称
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login(string $mobile,string $pwd,string $login_ip,string $equipment_name) : array
    {
        if (empty($mobile) || empty($pwd)) {
            return $this->error('用户名或密码错误');
        }
        $modelUser = new ModelUser();
        $where = [
            'mobile' => $mobile,
            'password' => $pwd,
            'is_delete' => 1 //逻辑删除 1:未删除 2 已删除
        ];
        $userInfo = $modelUser->where($where)->field('id,user_token,mobile')->findOrEmpty()->toArray();
        $t = time();
        if (empty($userInfo)) {
            $datalog = [
                'user_id' => 0,
                'login_ip' => $login_ip,
                'login_time' => $t,
                'login_status' => 2, //登录状态;1 登录成功后相关的日志; 2 登录失败相关的日志
                'login_num' => 1, //todo
                'equipment_name' => $equipment_name,
                'remark' => '用户登录失败,用户数据：' . json_encode($where),
            ];
            $this->insertUserLoginLog($datalog);
            return $this->error('登录失败,用户名或者密码错误');
        }
        $data = [
            'last_login_time' => $t,
            'is_online' => 1, //在线状态更新为1，退出后更新为0
            'token_lifecycle' => $t + 7200000,
        ];
        $result = $modelUser->where(['id' => $userInfo['id']])-> save($data);
        //echo  $modelUser -> getLastSql();
        //die();
        if ($result) {
            $datalog = [
                'user_id' => $userInfo['id'],
                'login_ip' => $login_ip,
                'login_time' => $t,
                'login_status' => 1,
                'login_num' => 1, //todo
                'equipment_name' => $equipment_name,
                'remark' => '用户：' . json_encode($userInfo) . '登录成功,登录成功后更新的用户数据：' . json_encode($data),
            ];
            $this->insertUserLoginLog($datalog);
            return $this->success('登录成功', $userInfo);
        }
    }


    /**
     * 用户退出登录
     * @param string $token
     * @param string $login_ip
     * @param string $equipment_name
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function loginOut(string $token,string $login_ip,string $equipment_name) : array {
        if (empty($token)) {
            return $this->error('非法访问');
        }
        $modelUer = new ModelUser();
        $result = $this -> getUserInfoByToken($token);
        if($result['status'] != 1){
            return $this->error('非法访问');
        }else{
            $data = [
                'is_online' => 0,
                'token_lifecycle' => -1,
              ];
            $update = $modelUer -> where(['id'=> $result['data']['id']]) -> save($data);
            if($update){
                $t = time();
                $datalog = [
                    'user_id' => $result['data']['id'],
                    'login_ip' => $login_ip,
                    'login_time' => $t,
                    'login_status' => 0,
                    'login_num' => 0, //todo
                    'equipment_name' => $equipment_name,
                    'remark' => '用户：' . json_encode($result['data']) . '退出成功,更新的用户数据：' . json_encode($data),
                ];
                $this->insertUserLoginLog($datalog);
                return $this->success('退出成功', 1);
            }
        }
    }

    /**
     * @param array $data
     * @return bool
     */
    public function insertUserLoginLog(array $data) : bool{
        if(empty($data)){
            return  false;
        }
        $modelUserLoginLog = new ModelUserLoginLog();
        $result_log_id = $modelUserLoginLog -> insertGetId($data);
        return $result_log_id>0;
    }

    /**
     * 获取宴请码:我新创建的用户创建唯一的邀请码
     */
    private function getInvitationCode():string
    {
        $code = ''; //保存生成的code码
        $char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; //26个字符
        $char2 = '0123456789ABCDEFGHIJKLMNOPQRSTUV'; //32个字符
        $data[0] = $char[mt_rand(0, 25)]; //值为A~Z
        $data[1] = strtoupper(dechex(Date('m', time()))); //值为1~C
        $data[2] = Date('d', time()); //值为1~31
        $data[3] = substr(time(), -5); //时间戳后5位
        $data[4] = substr(microtime(), 2, 5); //值为微秒的小数点后5位
        $data[5] = sprintf('%02d', rand(0, 99)); //值为0~99
        $str = implode('', $data); //合并为字符串
        $bin = md5($str, true); //16字节的二进制数据
        for ($i = 0; $i < 8; $i++) {
            $a8 = ord($bin[$i]); //$a8保存前8字节的循环数据
            $b8 = ord($bin[$i + 8]); //$b8保存后8字节的循环数据
            $index = ($a8 ^ $b8) - $a8 & 0x1F; //0x1F表示31，即$index的范围为0~31
            $code .= $char2[$index]; //根据下标取出$char2中字符串
        }
        return $code;
    }

    /**
     * @param int $user_id 用户ID
     * @return bool
     */
    private function insertUserAccount(int $user_id):bool
    {
        $modelUserAccount = new ModelUserAccount();
        $data = [
            'user_id' => $user_id,
            'balance' => 0,
            'frozen_balance' => 0,
            'create_time' => time()
        ];
        $result = $modelUserAccount->insertGetId($data);
        return  $result>0;
    }

    /**
     * 判断手机号是否唯一
     * @param string $mobile 注册时填写的用户手机号，全表唯一
     * @param int $user_id 如果用ID 不空，说明是要检查除自己的号码外是否有重复
     * @return int 用户表全部字段
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function isHaveUserMobile(string $mobile,int $user_id = 0): bool
    {
        if(empty($mobile)){
            return false;
        }
        $modelUser = new ModelUser();
        $where= [
            ['mobile' , '=' , $mobile]
        ];
        if($user_id >0){
            $where[] = [
               ['id','<>',$user_id]
            ];
        }
        $result = $modelUser -> where($where) -> count();
        return  $result > 0 ;
    }

    /**
     * 根据用户手机号获取用户信息
     * @param string $mobile 注册时填写的用户手机号，全表唯一
     * @return array 用户表全部字段
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserInfoByMobile(string $mobile): array
    {
        $modelUser = new ModelUser();
        $where= [
            'mobile' => $mobile
        ];
        $result = $modelUser -> where($where) ->findOrEmpty() -> toArray();
        return  $this -> success('成功',$result);
    }

    /**
     * 根据用户ID获取用户信息
     * @param string $id 用户表主键ID
     * @param string $filed 查询字段
     * @return array 用户表全部字段
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserInfoById(int $id,string $filed='*'): array
    {
        $modelUser = new ModelUser();
        $where= [
            'id' => $id
        ];
        $result = $modelUser -> where($where) ->field($filed) ->findOrEmpty() -> toArray();
        return  $this -> success('成功',$result);
    }

    /**
     * 获取用户信息
     * @param string $token
     * @param string $field 需要查询的字段，默认是：id,user_token,mobile
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function  getUserInfoByToken(string $token,string $field =''): array
    {
        if (empty($token)) {
           return $this->error('非法访问');
        }
        $modelUer = new ModelUser();
        $t = time();
        $where = [
            ['user_token', '=', $token],
            //['token_lifecycle', '>', $t ],
            ['is_online','=',1], //登录时写了这个状态等于1
            ['is_delete','=',1]
        ];
        if(empty($field)){
            $field = 'id,user_token,mobile,vip_lv';
        }
        $userBaseData = $modelUer->where($where) -> field($field) ->findOrEmpty() -> toArray();
        //dump($modelUer->getLastSql());die();
        if (!empty($userBaseData)) {
            return $this->success('成功', $userBaseData);
        } else {
            return $this->error('未查询到用户数据','100103');
        }
    }

    /**
     *  * 检查用户是否在线且返回用户关键信息
     * @param string $token
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function  checkUerIsOnlineByToken(string $token): array
    {
        if (empty($token)) {
            return $this->error('非法访问');
        }
        $userBaseData = $this->getUserInfoByToken($token);
        if ($userBaseData['status'] == 1 && !empty($userBaseData['data'])) {
            return $this->success('成功', $userBaseData['data']);
        } else {
            return $this->error('未查询到用户数据','100103');
        }
    }

    /**
     *通过用户ID获取用户账号数据
     * @param int $user_id 用户ID
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserAccountInfoByUserID(int $user_id) : array
    {
        if (empty($user_id)) {
           return $this->error('非法访问');
        }
        $modelUerAccount = new ModelUserAccount();
        $where = [
            'user_id' => $user_id
        ];
        $userAccount = $modelUerAccount->where($where) -> field('*') ->findOrEmpty() -> toArray();
        return $result =  $this->success('成功',$userAccount);
    }

    /**
     * 获取用收入信息，跟进用户ID和时间
     * @param int $user_id 用户ID
     * @param int $time  收入的时间
     * @param string $field 字段
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserAccountIncomeByUserID(int $user_id,int $time,string $field='') : array
    {
        if (empty($user_id)) {
            return $this->error('非法访问');
        }
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        if($time < 1  || $beginToday > time()){
            $time =  $beginToday;
        }
        $modelUerAccountIncome = new ModelUserAccountIncome();
        $where = [
            ['user_id','=', $user_id],
            ['create_time','>', $time],
        ];
        if(empty($field)){
            $field = '*';
        }
        $userAccountIncome = $modelUerAccountIncome->where($where) -> field($field) ->find() -> toArray();
        //dump($modelUerAccountIncome -> getLastSql());die();
        return $this->success('成功',$userAccountIncome);
    }



    /**
     *通过用户ID获取用户下级团队人数
     * @param int $user_id 用户ID
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserTeamUserNumByUserID(int $user_id) : array
    {
        if (empty($user_id)) {
            $this->error('非法访问');
        }
        $modelUer = new ModelUser();
        $where = [
            'lv_path' => ['sw_visitUrlFirst','like',$user_id.'-']
        ];
        $userBaseData = $modelUer->where($where)->count();
        return $result =  $this-> success('成功',$userBaseData);
       //var_dump($result); die();
    }

    /**
     *通过用户ID获取用户任务数量
     * @param int $user_id 用户ID，必传参数
     * @param string $status 任务状态 1:已领取未完成，2: 提交审核， 3:已领取已完成，支持多状态查询,默认为[1]
     * @param string $task_start_time_day 用户任务开始的时间--整天,例如:20210328,可选参数
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserTaskNumByUserIDAndStatus(int $user_id,string $status,string $task_start_time_day) : array
    {
        if (empty($user_id)) {
            $this->error('非法访问');
        }
        $modelUerTask = new ModelUserTask();
        $where = [
            'user_id' => $user_id,
        ];
        if (!empty($status)) {
            //$where['task_status'] = ['in', $status];
            $where['task_status'] = array('in',$status);
        }
        if (!empty($task_start_time_day)) {
            $where['task_start_time_day'] = $task_start_time_day;
        }
        //$userTaskData = $modelUerTask->where($where) ->whereIn('task_status',$status)->count();
        $userTaskData = $modelUerTask->where($where)->count();
        $result =  $this->success('成功', $userTaskData);
        return $result;
    }

    /**
     * @param int $vip_start_time 查询指定日期的VIP用户开通时间排序，从高到底排序，默认：查询60天内开通
     * @return array $list 用户的任务数量
     */
    public function getNewVipUserTopFive(int $vip_start_time):array
    {
        //会员等级 ：0:免费会员; 1:lv1 ; 2:lv2 ; 3:lv3 ;
        if(empty($vip_start_time)){
            $vip_start_time = strtotime("-60 day");
        }
        /*
        $list = Db::table('user_task')
            ->alias('ut')
            ->join('user u','u.id = ut.user_id')
            ->field('u.mobile,count(1) task_num')
            ->where(['ut.task_status'=>3])
            ->group('ut.user_id')
            ->order('id', 'desc')
            ->select();
        */

        $list = Db::query( "select u.mobile,u.vip_lv
from user u
     inner join user_vip_log ul on ul.user_id = u.id 
where u.vip_lv > ?
and ul.vip_start_time > ?
and ul.status = ?
order by ul.vip_start_time desc
limit 5" ,[0, $vip_start_time,1]);
       return $this->success('成功',$list);
    }

    /**
     * 重置用户密码--通过用户手机号
     * @param string $mobile 手机号
     * @param string $pwd 新密码
     * @return array
     */

    /**
     * 重置用户密码--通过用户手机号
     * @param string $mobile 手机号
     * @param string $pwd 新密码，已MD5加密过的
     * @param string $login_ip
     * @param string $equipment_name
     * @param string $captcha
     * @param int $captchaId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function resetPwdByMobile(string $mobile,string $pwd,string $login_ip,string $equipment_name
        ,string $captcha,int $captchaId) : array
    {
        if(empty($mobile) || empty($pwd) || empty($login_ip) || empty($equipment_name) || empty($captcha)
            || empty($captchaId)){
            return $this -> error('参数错误');
        }
        $userInfo = $this -> getUserInfoByMobile($mobile);
        if (empty($userInfo['data'])) {
            return $this->error('手机号错误');
        }
        /** 这个方法是不登录就可以调用的，不可以判断新旧密码是否相等
        if($userInfo['data']['password'] === $pwd){ //新密码，已MD5加密过的
            return $this->error('原密码');
        }
         */
        $t = time();
        $userModel = new ModelUser();
        $where = [
            'mobile' => $mobile
        ];
        $data = [
            'password' => $pwd, //传入时已加密
            //'mobile' => $mobile,
        ];
        $result_id = $userModel->where($where)->save($data);

        $remark = '用户重置密码,重置前用户数据：' . json_encode($userInfo).';新的密码：'.
            $pwd.';验证码和ID：'.$captcha.'-'.$captchaId;
        $datalog = [
            'user_id' => $userInfo['data']['id'],
            'login_ip' => $login_ip,
            'login_time' => $t,
            'login_status' => 0,
            'login_num' => 1, //todo
            'equipment_name' => $equipment_name,
        ];
        $msg = '重置密码成功;result_id：'.$result_id; //如果是0代表是原密码更新
        $datalog['remark'] = $msg . $remark;
        $this -> insertUserLoginLog($datalog);
        return $this->success($msg,1);
    }


    /**
     * 统计一个用户下级用户的数量
     * @param int $user_id 用户ID
     * @param bool $isVip  是否要统计子级的VIP用户数量
     * @param int $time 子级用户的注册时间
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function countUserSon(int $user_id,bool $isVip = false,int $time = 0 ) : array
    {
        if (empty($user_id)) {
            return $this->error('参数错误');
        }
        $where= [];
        if(!empty($time)){
            $where[] = ['reg_time','>',$time];
        }
        $result = Db::table('user')
            ->field('vip_lv,count(*) count')
            ->whereLike('lv_path', $user_id . '-%')
            ->where($where)
            ->group('vip_lv')
            ->select();
        return $this->success('成功', $result);
    }

    /**
     * 统计一个用户直接及下级每个级别的推广收益
     * @param int $user_id 用户ID
     * @param int $time 注册时间
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function countUserSonTuiGuangIncome(int $user_id,int $time=0) : array
    {
        if (empty($user_id)) {
            return $this->error('参数错误');
        }
        $where= [];
        if(!empty($time)){
            $where[] = ['u.reg_time','>',$time];
        }
        $result = Db::table('user')
            -> alias('u')
            ->join('user_account c ','c.user_id = u.id')
            ->field('u.vip_lv,sum(c.total_popularize_profit) total_popularize_profit')
            ->whereLike('u.lv_path', $user_id . '-%')
            ->where($where)
            ->group('u.vip_lv')
            ->select()
            ->toArray();
        return $this->success('成功', $result);
    }

    /**
     * 统计一个用户直接下级用户的信息
     * @param int $user_id 用户ID
     * @param int $time 徒弟注册的时间
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserSonList(int $user_id,int $time=0) : array
    {
        if (empty($user_id)) {
            return $this->error('参数错误');
        }
        $where = [
            ['pid','=',$user_id]
        ];
        if(!empty($time)){
            $where[] = ['reg_time','>',$time];
        }
        $result = Db::table('user')
            ->field('*')
            ->where($where)
            ->select()
            ->toArray();
        return $this->success('成功', $result);
    }

    /**
     * 查询用户信息--通过信息ID数组
     * @param array $user_ids 用户ID，多个
     * @param string $field 查询字段
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserListByIds(string $user_ids,string $field='*') : array
    {
        if (empty($user_ids)) {
            return $this->error('参数错误');
        }
        $result = Db::table('user')
            ->field($field)
            ->whereIn('id',$user_ids)
            ->order('lv desc') //一定要用ID排序
            ->select()
            ->toArray();
        //var_dump( Db::table('user') -> getLastSql()); die();
        return $this->success('成功', $result);
    }


    /**
     * 更新用户VIP级别或者更新禁用状态
     * @param int $user_id
     * @param int $vip_lv
     * @param int $is_delete
     * @param $amount 如果是VIP充值，则记录充值金额，非必填
     * @return array
     */
    public function updateUserStatusByID(int $user_id,int $vip_lv,int $is_delete=0,$amount=0) : array
    {
        if (empty($user_id)) {
            return $this->error('参数错误');
        }
        $data = [];
        if ($vip_lv > 0 && $vip_lv <= 7) {
            $data = [
                'vip_lv' => $vip_lv
            ];
        }
        if ($is_delete == 1 || $is_delete == 2) {
            $data = [
                'is_delete' => $is_delete
            ];
        }
        $userModel = new ModelUser();
        $result = $userModel->where('id', $user_id)->save($data);
        if ($result) {
            if ($vip_lv > 0) {  //开通VIP执行此逻辑，后面可能有VIP失效也走这里
                $day = $this->getVipDayByVipLv($vip_lv);
                $time_day = date('Ymd');
                $remark = '开通VIP成功,级别:lv' . $vip_lv . '级,费用：' . $amount . '元,有效天数:' . $day . '从' . $time_day . '日开始';
                $r = $this->insertUserVipLog($user_id, $vip_lv, $amount, $time_day, $day, $remark);
                if($r['status'] == 0){
                    return $this->error($r['msg']);
                }else{
                    return $this->success('成功', $r['data']);
                }
            }
        } else {
            return $this->error('更新用户数据失败');
        }
    }


    /**
     * 插入用户开通或者注销VIP的信息
     * @param int $user_id 用户ID
     * @param int $vip_lv VIP级别
     * @param string $amount 开通VIP的金额
     * @param int $startTime VIP 生效时间
     * @param int $day 有效天数
     * @param  string $remark 备注
     * @return array
     */
    public function insertUserVipLog(int $user_id,int $vip_lv,string $amount,int $startTime,int $day,string $remark) : array
    {
        if (empty($user_id) || empty($vip_lv) || empty($amount) || empty($startTime) || empty($day)) {
            return $this->error('参数错误');
        }
        $userModel = new ModelUserVipLog();
        $data = [
            'user_id' => $user_id,
            'vip_start_time' => $startTime,
            'vip_expiration_time' => $startTime + $day,
            'vip_lv' => $vip_lv,
            'vip_money' => $amount,
            'status' => 1,
            'create_time' => time(),
            'remark' => $remark
        ];
        $result = $userModel->insertGetId($data);
        if ($result) {
            return $this->success('成功',$result);
        } else {
            return $this->error('失败');
        }
    }

    /**
     * 编辑用户基本信息--根据不同字段更新
     * @param int $user_id 用户ID
     * @param array $data 根据前端用户插入的数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function editUserInfoById(int $user_id,array $data) : array
    {
        if (empty($user_id) || empty($data['equipment_name']) || empty($data['ip'])) {
            return $this->error('必要参数不可位空');
        }
        $result = false;
        $userModel = new ModelUser();
        $new_data = [];
        if (!empty($data['head_img'])) {
            $new_data['head_img_url'] = $data['head_img'];
        }
        if (!empty($data['nick_name'])) {
            $new_data['real_name'] = $data['nick_name'];
        }
        if (!empty($data['sex'])) {
            $new_data['sex'] = $data['sex'];
        }
        if (!empty($data['address'])) {
            $new_data['addr'] = $data['address'];
        }
        if (!empty($data['mobile'])) {
            $isHave = $this->isHaveUserMobile($data['mobile'], $data['user_id']);
            if ($isHave) {
                return $this->error('手机号已存在', 1);
            }
            $new_data['mobile'] = $data['mobile'];
            $new_data['is_online'] = 0;
            $new_data['token_lifecycle'] = -1;
        }
        if (!empty($data['pwd'])) {
            $new_data['password'] = md5($data['pwd']);
            $new_data['is_online'] = 0;
            $new_data['token_lifecycle'] = -1;
        }
        if (!empty($data['old_pwd'])) {
            $my_where = [
                'id' => $user_id,
                'password' => md5($data['pwd'])
            ];
            $check = $userModel->where($my_where)->count();
            if ($check = 0) {
                return $this->error('原密码错误');
            }
        }
        //dump('wwww');
        $result = $userModel->where('id', $user_id)->save($new_data);
        //dump($userModel -> getLastSql());die();
        $t = time();
        $regMsg = $result ? '成功' : '失败';
        $datalog = [
            'user_id' => $user_id,
            'login_ip' => $data['ip'],
            'login_time' => $t,
            'login_status' => 1,
            'login_num' => 1, //todo
            'equipment_name' => $data['equipment_name'],
            'remark' => '用户：' . $user_id . ',修改信息：' . $regMsg . ',用户数据：' . json_encode($new_data),
        ];
        //dump($datalog);die();
        //如果日志插入失败，则不管
        $this->insertUserLoginLog($datalog);
        if ($result) {
            return $this->success('更新成功');
        } else {
            return $this->error('更新失败或者数据没变化');
        }
    }

    /**
     * 重置手机号
     * @param int $user_id  用户id
     * @param string $mobile_old 原手机号
     * @param string $mobile 新手机号
     * @param string $ip 操作人的IP
     * @param string $equipment_name 设备名称
     * @return array
     */
    public function resetMobile(int $user_id,string $mobile_old,string $mobile,string $ip,string $equipment_name) : array{
        if(empty($user_id) || empty($mobile_old) || empty($mobile) || empty($ip)  || empty($equipment_name)){
            return $this->error('参数错误');
        }
        $isHave = $this->isHaveUserMobile($mobile, $user_id);
        if ($isHave) {
            return $this->error('手机号已存在');
        }
        $userModel = new ModelUser();
        $new_data = [];
        $new_data['mobile'] = $mobile;
        $new_data['is_online'] = 0;
        $new_data['token_lifecycle'] = -1;

        $where= [
            'id' => $user_id,
            'mobile' => $mobile_old,
        ];
        $result = $userModel->where($where)->save($new_data);
        //dump($userModel -> getLastSql());die();
        $t = time();
        $regMsg = $result ? '成功' : '失败';
        $datalog = [
            'user_id' => $user_id,
            'login_ip' => $ip,
            'login_time' => $t,
            'login_status' => 1,
            'login_num' => 1, //todo
            'equipment_name' => $equipment_name,
            'remark' => '用户：' . $user_id . ',修改信息：' . $regMsg . ',用户数据：' . json_encode($new_data),
        ];
        //如果日志插入失败，则不管
        $this->insertUserLoginLog($datalog);
        if ($result) {
            return $this->success('更新成功');
        } else {
            return $this->error('更新失败或者数据没变化');
        }
    }


}